package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.exception.*;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.pojo.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.admin.EmployeeService;
import com.sky.utils.IdentityUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import com.sky.vo.EmployeeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {


    @Resource
    private EmployeeMapper employeeMapper;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        // 参数校验
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new ParameterIsNullException(MessageConstant.USERNAME_OR_PASSWORD_IS_NULL);
        }

        // 1、根据用户名查询数据库中的数据  select * from employee where username = #{username}
        Employee employee = employeeMapper.getByUsername(username);

        // 2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 加密明文密码，并比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (StatusConstant.DISABLE.equals(employee.getStatus())) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 3、登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();
        return employeeLoginVO;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void addEmployee(EmployeeDTO employeeDTO) {
        // 参数校验：账号唯一、手机号合法11位、身份证合法18位、密码默认123456加密
        if (Objects.nonNull(employeeMapper.getByUsername(employeeDTO.getUsername()))) {
            throw new EmployeeNameExistException(MessageConstant.EMPLOYEE_USERNAME_EXIST);
        }
        if (!IdentityUtil.validatePhone(employeeDTO.getPhone())) {
            throw new ParameterInvalidException(MessageConstant.PHONE_IS_INVALID);
        }
        if (!IdentityUtil.validateIdCardNum(employeeDTO.getIdNumber())) {
            throw new ParameterInvalidException(MessageConstant.ID_NUMBER_IS_INVALID);
        }
        // copyProperties方法只有数据类型跟属性名都相同的情况下，才能拷贝成功
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        // 补全属性
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        // 保存员工
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult<EmployeeVO> getPageList(EmployeePageQueryDTO employeePageQueryDTO) {
        // 参数校验
        int page = employeePageQueryDTO.getPage();
        int pageSize = employeePageQueryDTO.getPageSize();
        if (page <= 0 || pageSize <= 0) {
            throw new ParameterInvalidException("分页参数不合法");
        }
        //   开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> employees = employeeMapper.selectPageList(employeePageQueryDTO.getName());
        // 封装EmployeeVO对象
        List<EmployeeVO> employeeVOS = employees.getResult().stream().map(o -> {
            EmployeeVO employeeVO = new EmployeeVO();
            BeanUtils.copyProperties(o, employeeVO);
            return employeeVO;
        }).toList();
        return new PageResult<>(employees.getTotal(), employeeVOS);
    }

    @Override
    public EmployeeVO getEmployeeById(Long id) {
        // 参数校验
        if (Objects.isNull(id)) {
            throw new ParameterIsNullException(MessageConstant.ID_IS_NULL);
        }
        Employee employee = employeeMapper.selectById(id);
        if (Objects.isNull(employee)) {
            throw new EmployeeNotExistException(MessageConstant.EMPLOYEE_NOT_FOUND);
        }
        // 数据脱敏转换VO
        EmployeeVO employeeVO = new EmployeeVO();
        BeanUtils.copyProperties(employee, employeeVO);
        return employeeVO;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void modifyEmployeeById(EmployeeDTO employeeDTO) {
        // 参数校验：账号唯一、手机号合法11位、身份证合法18位、密码默认123456加密
        if (Objects.nonNull(employeeMapper.getByUsername(employeeDTO.getUsername()))) {
            throw new EmployeeNameExistException(MessageConstant.EMPLOYEE_USERNAME_EXIST);
        }
        if (!IdentityUtil.validatePhone(employeeDTO.getPhone())) {
            throw new ParameterInvalidException(MessageConstant.PHONE_IS_INVALID);
        }
        if (!IdentityUtil.validateIdCardNum(employeeDTO.getIdNumber())) {
            throw new ParameterInvalidException(MessageConstant.ID_NUMBER_IS_INVALID);
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        // 修改
        employeeMapper.updateById(employee);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void disableOrEnableEmpStatus(Integer status, Long id) {
        // 参数校验
        if(Objects.isNull(id)){
            throw new ParameterIsNullException(MessageConstant.ID_IS_NULL);
        }
        if(Objects.isNull(status)){
            throw new ParameterIsNullException(MessageConstant.EMPLOYEE_STATUS_IS_NULL);
        }
        if(!StatusConstant.DISABLE.equals(status) && !StatusConstant.ENABLE.equals(status)){
            throw new EmployeeStatutsInvalidException(MessageConstant.EMPLOYEE_STATUS_IS_INVALID);
        }
        // 构建员工对象
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        // 修改员工信息
        employeeMapper.updateById(employee);
    }
}
